from paste.httpexceptions import HTTPFound
from enlargeweb.model.user import User
from enlargeweb.model import meta
from pylons.controllers.util import abort
from pylons import request
import hashlib, logging

log = logging.getLogger(__name__)

class UserModelPlugin(object):
	'''
		Plugin provides access to enlargeweb.model.user.User
		obejcts, generic auth tokens objects
	'''
	
	def authenticate(self, environ, identity):
		'''
			Try to find user in DB and check
			if supplied hashed password is the same as
			one we store
		'''
		try:
			username = identity['login']
			password = identity['password']
			log.debug('Authenticate: %s' % username)
		except KeyError:
			log.fatal('AUTH: Login or Password is empty')
			return None
		try:
			known_user = meta.Session.query(User).filter(User.login == str(username)).one()		
		except Exception, ex:
			log.fatal('AUTH: No such user')
			return None
			
		if hashlib.md5(password).hexdigest() != known_user.password:
			log.fatal('AUTH: Password HASH mismatch')
			return None
		
		return known_user.id

	def add_metadata(self, environ, identity):
		'''
			Add metadata to user identity record
			Since we are the plugin who handles such
			operations
		'''
		log.debug('Adding metadata')
		user_id = identity.get('repoze.who.userid')
		log.debug('Identity from repoze.who: %s' % user_id)
		user = meta.Session.query(User).filter(User.id == user_id).one()
		if user is not None:
			log.debug('User: %s' % user)
			identity['auth_tkt'] = user
			